//
//  NSObject+HEMSViewController.m
//  bp
//
//  Created by TeemoYang on 2023/7/29.
//

#import "NSObject+ViewController.h"

@implementation NSObject (ViewController)

- (UIViewController *)currentViewController {
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    return [self getCurrentViewControllerFrom:rootViewController];
}

- (UIViewController *)getCurrentViewControllerFrom:(UIViewController *)viewController {
    if ([viewController isKindOfClass:[UINavigationController class]] ||
        [viewController isKindOfClass:[UITabBarController class]]) {
        if ([viewController isKindOfClass:[UINavigationController class]]) {
            UINavigationController *navController = (UINavigationController *)viewController;
            return [self getCurrentViewControllerFrom:navController.visibleViewController];
        } else if ([viewController isKindOfClass:[UITabBarController class]]) {
            UITabBarController *tabBarController = (UITabBarController *)viewController;
            return [self getCurrentViewControllerFrom:tabBarController.selectedViewController];
        }
    }
    
    if (viewController.presentedViewController) {
        return [self getCurrentViewControllerFrom:viewController.presentedViewController];
    }
    
    return viewController;
}

@end
